package tr.gov.tubitak.uekae.esya.api.smartcard.example.pfx;

import junit.framework.TestCase;
import tr.gov.tubitak.uekae.esya.api.asn.x509.ECertificate;
import tr.gov.tubitak.uekae.esya.api.cades.example.testconstans.TestConstants;
import tr.gov.tubitak.uekae.esya.api.common.util.bag.Pair;
import tr.gov.tubitak.uekae.esya.api.crypto.util.PfxParser;
import tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.CardType;
import tr.gov.tubitak.uekae.esya.api.smartcard.pkcs11.SmartCard;

import java.io.FileInputStream;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.util.List;

public class LoadPfx extends TestCase
{
	public void testLoadPfx() throws Exception
	{
		SmartCard sc = new SmartCard(CardType.AKIS);
		//Dogrudan ilk karta baglanılıyor.
		long session = sc.openSession(1);
		//PIN
		sc.login(session, TestConstants.getPIN());
		
		//Pfx okunuyor.
		FileInputStream fis = new FileInputStream("sertifika deposu/356265 _test1@kamusm.gov.tr.pfx");
		PfxParser pfxParser = new PfxParser(fis, "356265".toCharArray());
		List<Pair<ECertificate, PrivateKey>> entries = pfxParser.getCertificatesAndKeys();
		
		
		for (Pair<ECertificate, PrivateKey> pair : entries) 
		{
			ECertificate cert = pair.getObject1();
			KeyPair keyPair = new KeyPair(cert.asX509Certificate().getPublicKey(), pair.getObject2());
			
			String label = "Test Sertifikasi";
		
			//Anahtar çifti ve sertifika karta yükleniyor.
			sc.importKeyPair(session, label, keyPair,  null, true, false);
			sc.importCertificate(session, label, cert.asX509Certificate());
		}
	}
}
